<script setup lang="ts">
// 引入 Vue 的 Composition API
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
// 引入 echarts 库
import * as echarts from 'echarts'

// 获取 DOM 元素的引用（用于初始化图表）
const chartRef = ref(null)
// 存储 ECharts 实例
let chartInstance: echarts.ECharts | null = null

// 初始化圆饼图的方法
const initChart = () => {
  if (chartRef.value) {
    // 初始化 echarts 实例
    chartInstance = echarts.init(chartRef.value)

    // 配置项
    const option = {
      backgroundColor: '#ffffff',

      title: {
        text: 'Customized Pie',
        left: 'center',
        top: 20,
        textStyle: {
          color: '#ccc'
        }
      },

      tooltip: {
        trigger: 'item'
      },

      visualMap: {
        show: false,
        min: 80,
        max: 600,
        inRange: {
          colorLightness: [0, 1]
        }
      },
      series: [
        {
          name: 'Access From',
          type: 'pie',
          radius: '55%',
          center: ['50%', '50%'],
          data: [
            { value: 335, name: 'Direct' },
            { value: 310, name: 'Email' },
            { value: 274, name: 'Union Ads' },
            { value: 235, name: 'Video Ads' },
            { value: 400, name: 'Search Engine' }
          ].sort(function (a, b) {
            return a.value - b.value;
          }),
          roseType: 'radius',
          label: {
            color: 'rgb(16,190,239)'
          },
          labelLine: {
            lineStyle: {
              color: 'rgb(22,230,186)'
            },
            smooth: 0.2,
            length: 10,
            length2: 20
          },
          itemStyle: {
            color: '#c23531',
            shadowBlur: 200,
            shadowColor: 'rgb(105,200,227)'
          },

          animationType: 'scale',
          animationEasing: 'elasticOut',
          animationDelay: function (idx: number) {
            return Math.random() * 200;
          }
        }
      ]
    }

    // 使用配置项渲染图表
    chartInstance.setOption(option)
  }
}

// 窗口大小变化时调整图表尺寸
const resizeChart = () => {
  if (chartInstance) {
    chartInstance.resize({
      animation: {
        duration: 300
      }
    })
  }
}

// 组件挂载后执行初始化
onMounted(() => {
  nextTick(() => {
    initChart()
    // 监听窗口大小变化事件以支持响应式
    window.addEventListener('resize', resizeChart)
  })
})

// 组件卸载前清理资源，防止内存泄漏
onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart)
  chartInstance?.dispose() // 销毁 echarts 实例
})
</script>

<template>
  <div class="round-cake-chart">
    <!-- 图表容器 -->
    <div ref="chartRef" class="chart-container"></div>
  </div>
</template>

<style scoped>
.round-cake-chart {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.chart-container {
  width: 100%;
  height: 100%;
  position: relative;
}
</style>
